package main

import (
	"database/sql"
	"fmt"

	_ "github.com/go-sql-driver/mysql"
)

func connectToMySQL() (*sql.DB, error) {
	db, err := sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/test")
	if err != nil {
		return nil, err
	}
	return db, nil
}

func queryData(db *sql.DB) {
	rows, err := db.Query("SELECT id, username FROM user")
	if err != nil {
		fmt.Println("Error querying data:", err)
		return
	}
	defer rows.Close()

	for rows.Next() {
		var id int
		var name string
		if err := rows.Scan(&id, &name); err != nil {
			fmt.Println("Error scanning row:", err)
			return
		}
		fmt.Println("User ID:", id, "Name:", name)
	}
}

func insertData(db *sql.DB, name string) error {
	_, err := db.Exec("INSERT INTO users (name) VALUES (?)", name)
	if err != nil {
		return err
	}
	return nil
}

func main() {
	db, err := connectToMySQL()
	if err != nil {
		fmt.Println("Error connecting to MySQL:", err)
		return
	}
	defer db.Close()

	queryData(db)

	err = insertData(db, "John Doe")
	if err != nil {
		fmt.Println("Error inserting data:", err)
		return
	}
}
